//
//  AppLoader.m
//  iCodeMac
//
//  Created by Andrew Barry on 27/02/09.
//  Copyright 2009 Barry Computer Services. All rights reserved.
//

#import "AppLoader.h"
#import "SourceEditor.h"
#import "ControlPanel.h"
#import "documents.h"
#import "WrappedJsval.h"
//#import "AppStack.h"
//#import "jvm.h"


jscontext *mainContext;
jscontext *buildContext;

jscontext * runMain();
jscontext * runBuild();
void registerDocuments(jscontext *cx);

NSMutableDictionary *startupWindowDefn, *debugPanelDefn, *projectPropertiesDefn;

static AppLoader *gAppLoader;

@implementation AppLoader

+(id) handlerForProjectType: (NSString *) projType {
	for (int idx = 0; idx < [gAppLoader->registeredTargets count]; idx++) {
		id handler = [gAppLoader->registeredTargets objectAtIndex:idx];
		if ([projType isEqualToString:[handler identifier]])
			return handler;
	}
	return nil;
}

-(void) awakeFromNib {
	gAppLoader = self;
	registeredTargets = [NSMutableArray new];
	NSFileManager *mgr = [NSFileManager defaultManager];
	NSString *targetsPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"Targets"];
	NSArray *targets = [mgr contentsOfDirectoryAtPath:targetsPath error:nil];
	if (targets) {
		for (int idx = 0; idx < [targets count]; idx++) {
			NSString *targetName = [targets objectAtIndex:idx];
			if ([[targetName pathExtension] isEqualToString: @"bundle"]) {
				NSString *bundlePath = [targetsPath stringByAppendingPathComponent:targetName];
				
				NSBundle *bundle = [NSBundle bundleWithPath:bundlePath];
				if (bundle != nil) {
					Class principalClass = [bundle principalClass];
					
					if(principalClass) {
						id targetHandler = [[principalClass alloc] init];
						NSString *targetName = [targetHandler name];
						[registeredTargets addObject: targetHandler];
						[newProjectType addItemWithTitle:targetName];
					}
				}
			}
		}
	}
	
	
	
	mainContext = runMain();
	buildContext = runBuild();
	registerDocuments(mainContext);
//	initializeRuntime();
	
	WrappedJsval *sys = [WrappedJsval wrap:mainContext->slots[13] withContext: mainContext];
	[sys invoke:@"showStartupWindow" args:[NSArray arrayWithObjects: nil]];
/*
	NSString *standardPath = [[NSBundle mainBundle] pathForResource:@"icmSysStandard" ofType:@"js"];
	NSString *standardContent = [NSString stringWithContentsOfFile:standardPath];
	runScript(@"icmSysStandard.js", standardContent);
	standardPath = [[NSBundle mainBundle] pathForResource:@"icmSysOSX" ofType:@"js"];
	standardContent = [NSString stringWithContentsOfFile:standardPath];
	runScript(@"icmSysOSX.js", standardContent);
	
	FormLoader *loader = [FormLoader new];
	
	NSString *path = [[NSBundle mainBundle] pathForResource:@"Window" ofType:@"jsfrm"];
	startupWindowDefn = [[NSMutableDictionary alloc] initWithContentsOfFile:path];
	debugPanelDefn = [[NSMutableDictionary alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"DebugPanel" ofType:@"jsfrm"]];
	projectPropertiesDefn = [[NSMutableDictionary alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"ProjectProperties" ofType:@"jsfrm"]];

	[loader compileForm:startupWindowDefn withFile:@"Window.jsfrm"];
	[loader compileForm:debugPanelDefn withFile:@"DebugPanel.jsfrm"];
	[loader compileForm:projectPropertiesDefn withFile:@"ProjectProperties.jsfrm"];
	[loader release];
	*/
//	SourceEditor *editor = [SourceEditor new];
//	[editor openWindow];
		/*
	NSArray *paths = NSSearchPathForDirectoriesInDomains(NSApplicationSupportDirectory, NSUserDomainMask, YES);
	NSString *path = [paths objectAtIndex:0];
	NSString *icmPath = [path stringByAppendingPathComponent:@"iCodeMac"];

	NSFileManager *mgr = [NSFileManager defaultManager];
	if (![mgr fileExistsAtPath:icmPath])
		[mgr createDirectoryAtPath:icmPath attributes:nil];
	NSString *homeStack = [icmPath stringByAppendingPathComponent:@"home.iCodeMac"];
	

	AppStack *stack = [[AppStack alloc] initWithPath: homeStack];
	[stack showAsWindow];
	[stack switchToEditor];
*/	
//	[[ControlPanel sharedPanel] show];
}

-(BOOL)applicationShouldOpenUntitledFile:(NSApplication *)sender {
	return NO;
}

- (void)applicationDidFinishLaunching:(NSNotification *)aNotification {
	if ([[[NSDocumentController sharedDocumentController] documents] count] > 0)
		return;
	/*
	FormLoader *loader = [FormLoader new];

	NSWindow *wnd = [loader newWindow:startupWindowDefn];
	JSObject *wndObj = [loader loadForm:startupWindowDefn into:wnd];
	[[WrappedJsval alloc] initWithVal:OBJECT_TO_JSVAL(wndObj)];
	[loader startForm: wndObj];

	[wnd makeKeyAndOrderFront:self];
	 */
}

-(void) newProject: (id) sender {
	NSSavePanel *panel = [NSSavePanel savePanel];
	[panel setRequiredFileType:@"jsprj"];
	[panel setTitle: @"New Project"];
	[panel setAccessoryView:newProjectAccessory];
	if (NSFileHandlingPanelOKButton == [panel runModal]) {
		int projectType = [newProjectType indexOfSelectedItem];
		NSString *path = [panel filename];
		NSString *folder = [path stringByDeletingLastPathComponent];
		
		// save new project
		NSMutableDictionary *newProject = [NSMutableDictionary dictionaryWithCapacity:1];

		bool consoleApp = false;

		id targetHandler = [registeredTargets objectAtIndex:projectType];
		NSString *projType = [targetHandler identifier];
		
		[newProject setObject:projType forKey:@"projType"];

		NSString *sourceName;
		
		if (consoleApp)
			sourceName = @"Source.js";
		else
			sourceName = @"Window.jsfrm";

		NSFileManager *fmgr = [NSFileManager defaultManager];
		int nameCounter = 1;
		while ([fmgr fileExistsAtPath:[folder stringByAppendingPathComponent:sourceName]] && nameCounter < 20) {
			if (consoleApp)
				sourceName = [NSString stringWithFormat:@"Source%d.jsfrm", nameCounter, nil];
			else
				sourceName = [NSString stringWithFormat:@"Window%d.jsfrm", nameCounter, nil];
			nameCounter++;
		}
		NSString *sourcePath = [folder stringByAppendingPathComponent:sourceName];

		NSMutableArray *fileList = [NSArray arrayWithObject:sourceName];
		[newProject setObject:fileList forKey:@"items"];
		
		NSData *projectContent = [NSPropertyListSerialization dataFromPropertyList:newProject format:NSPropertyListXMLFormat_v1_0 errorDescription:nil];
		[projectContent writeToFile:path atomically:NO];
		
		// Save new window
		if (consoleApp) {
			[@"println('Hello world');\n" writeToFile:sourcePath atomically:YES];
		} else {
			NSMutableDictionary *newWindow = [NSMutableDictionary dictionaryWithCapacity:1];
			[newWindow setObject:projType forKey:@"projType"];
			[newWindow setObject:[NSNumber numberWithInt:1] forKey:@"startup"];
			[newWindow setObject:[NSNumber numberWithInt:768] forKey:@"width"];
			[newWindow setObject:[NSNumber numberWithInt:1024] forKey:@"height"];
			[newWindow setObject:@"Untitled" forKey:@"title"];
			NSData *windowContent = [NSPropertyListSerialization dataFromPropertyList:newWindow format:NSPropertyListXMLFormat_v1_0 errorDescription:nil];
			[windowContent writeToFile:sourcePath atomically:NO];
		}
		
		[[NSDocumentController sharedDocumentController] openDocumentWithContentsOfURL:[NSURL fileURLWithPath:path] display:YES error:nil];
		[[NSDocumentController sharedDocumentController] openDocumentWithContentsOfURL:[NSURL fileURLWithPath:sourcePath] display:YES error:nil];
	}
}
/*
-(void)debugRun:(id) sender {
}

-(void)debugStop: (id) sender {
}
*/
@end
